﻿// project      : soapi-notify 
// purpose      : console and growl notifications of new Stack Exchange questions
// source       : http://soapi.info/tools/notify.aspx
// announcement : http://stackapps.com/questions/820
// website      : http://soapi.info/tools/notify.aspx
// license      : MIT/X11 - Copyright (c) 2010 Sky Sanders - See License.txt
// inspiration  : http://stackapps.com/questions/817/senotify-se-new-question-notification
// 
//  
using System;
using System.Collections.Generic;

namespace Soapi.Notify
{
    public class UpdateCache
    {
        private readonly Dictionary<string, List<string>> _cache;

        public UpdateCache()
        {
            _cache = new Dictionary<string, List<string>>();
        }

        public List<KeyValuePair<string, string>> GetUpdateList(int segmentLength)
        {
            var result = new List<KeyValuePair<string, string>>();

            foreach (string site in _cache.Keys)
            {
                string segment = string.Empty;

                foreach (string id in _cache[site])
                {
                    string token = String.Format("{0};", id);
                    if ((segment + token).Length > segmentLength)
                    {
                        result.Add(new KeyValuePair<string, string>(site, segment.Trim(';')));
                        segment = token;
                    }
                    else
                    {
                        segment += token;
                    }
                }

                if (segment.Length > 0)
                {
                    result.Add(new KeyValuePair<string, string>(site, segment.Trim(';')));
                }
            }

            return result;
        }

        public void Add(string site, string questionId)
        {
            if (Contains(site, questionId))
            {
                return;
            }

            if (!_cache.ContainsKey(site))
            {
                _cache[site] = new List<string>();
            }

            lock (_cache)
            {
                _cache[site].Add(questionId);
            }
        }

        public void Remove(string site, string questionId)
        {
            if (Contains(site, questionId))
            {
                lock (_cache)
                {
                    _cache[site].Remove(questionId);
                }
            }
        }

        public bool Contains(string site, string questionId)
        {
            if (!_cache.ContainsKey(site))
            {
                return false;
            }

            return _cache[site].Contains(questionId);
        }
    }
}